package com.qlylkj.lbk.ui.mine

import android.view.View
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.bumptech.glide.request.RequestOptions
import com.forest.core.etx.getCompatColor
import com.forest.core.etx.load
import com.forest.core.etx.startKtxActivity
import com.forest.core.etx.toast
import com.forest.core.widget.dialog.FDialog
import com.forest.core.widget.dialog.FDialogInterface
import com.forest.core.widget.dialog.Options
import com.jeremyliao.liveeventbus.LiveEventBus
import com.qlylkj.lbk.R
import com.qlylkj.lbk.app.PreferenceHelper
import com.qlylkj.lbk.app.addHost
import com.qlylkj.lbk.base.BaseVMFragment
import com.qlylkj.lbk.model.event.LiveEvent
import com.qlylkj.lbk.share.ShareSceneDialogFragment
import com.qlylkj.lbk.ui.company.CompanyInfoActivity
import com.qlylkj.lbk.ui.user.authentication.IdentityAuthActivity
import com.tencent.bugly.beta.Beta
import com.ysyc.ytszapp.share.ShareScene
import kotlinx.android.synthetic.main.fragment_mine.*

class MineFragment : BaseVMFragment<MineViewModel>() {

    companion object {
        fun newInstance(): MineFragment {
            return MineFragment()
        }
    }

    private var mShareSceneList = mutableListOf(
        ShareScene(ShareScene.SHARE_SCENE_WX_SESSION, R.mipmap.ic_share_wechat, "微信"),
        ShareScene(ShareScene.SHARE_SCENE_WX_TIMELINE, R.mipmap.ic_share_qq, "QQ"),
        ShareScene(ShareScene.SHARE_SCENE_SAVE_PICTURE, R.mipmap.ic_share_weibo, "微博")
    )

    override fun providerVMClass() = MineViewModel::class.java

    override fun setLayoutId() = R.layout.fragment_mine

    override fun initView() {
        LiveEventBus.get(LiveEvent.LOGIN_KEY, Boolean::class.java)
            .observeSticky(this, Observer<Boolean> {
                getUserInfo()
            })
        userCompanyNameText.setOnClickListener(onClickListener)
        userNameText.setOnClickListener(onClickListener)
        identityAuthenticationLayout.setOnClickListener(onClickListener)
        removeBindLayout.setOnClickListener(onClickListener)
        shareAppLayout.setOnClickListener(onClickListener)
        contactUsLayout.setOnClickListener(onClickListener)
        versionUpdateLayout.setOnClickListener(onClickListener)
        logoutLayout.setOnClickListener(onClickListener)
        messageNotificationSwitch.setOnCheckedChangeListener { _, isChecked ->
            PreferenceHelper.messageNotificationSwitch = isChecked
        }
        messageNotificationSwitch.isChecked = PreferenceHelper.messageNotificationSwitch
    }

    override fun initData() {

    }

    override fun startObserve() {
        super.startObserve()
        mViewModel.apply {
            uiState.observe(this@MineFragment, Observer { uiModel ->
                uiModel?.run {
                    if (getUserInfoSuccess) {
                        setUserInfoView()
                    }
                    if (removeBindSuccess) {
                        activity?.toast("解除绑定成功")
                        getUserInfo()
                    }
                    showError?.let {
                        activity?.toast(it)
                    }
                }
            })
        }
    }

    override fun onResume() {
        super.onResume()
        getUserInfo()
    }

    private fun getUserInfo() {
        if (PreferenceHelper.isLogin) {
            mViewModel.getUserInfo()
        } else {
            defaultUserView()
        }
    }

    private fun setUserInfoView() {
        if (PreferenceHelper.isLogin) {
            logoutLayout.isVisible = true
            PreferenceHelper.getUserInfo({
                it.apply {
                    activity?.run {
                        headImage.load(
                            this,
                            headImg.addHost(),
                            RequestOptions().placeholder(R.mipmap.ic_user_head_default)
                        )
                        userCompanyNameText.text = companyName ?: "您暂未认领公司"
                        userNameText.text = username
                        when (bindingStatus) {
                            0 -> {
                                authenticationStatusText.text = "认证中"
                                authenticationStatusText.setTextColor(getCompatColor(R.color.text_primary))
                            }
                            1 -> {
                                authenticationStatusText.text = "已认证"
                                authenticationStatusText.setTextColor(getCompatColor(R.color.text_title))
                            }
                            else -> {
                                authenticationStatusText.text = "未认证"
                                authenticationStatusText.setTextColor(getCompatColor(R.color.text_desc))
                            }
                        }
                    }
                }
            })
        } else {
            defaultUserView()
        }
    }

    private fun defaultUserView() {
        activity?.run {
            headImage.load(
                this,
               "",
                RequestOptions().placeholder(R.mipmap.ic_user_head_default)
            )
        }
        userCompanyNameText.text = "您暂未认领公司"
        userNameText.text = getString(R.string.click_login_app)
        logoutLayout.isVisible = false
    }

    private val onClickListener = View.OnClickListener {
        if (isLoginPrompt()) {
            when (it.id) {
                R.id.userCompanyNameText -> toCompanyInfo()
                R.id.identityAuthenticationLayout -> toIdentityAuthentication()
                R.id.removeBindLayout -> removeBind()
                R.id.shareAppLayout -> shareApp()
                R.id.contactUsLayout -> toContactUs()
                R.id.versionUpdateLayout -> versionUpdate()
                R.id.logoutLayout -> logout()
                else -> {
                }
            }
        }
    }

    private fun toCompanyInfo() {
        PreferenceHelper.getUserInfo({
            it.apply {
                if (bindingStatus == 1) {
                    startKtxActivity<CompanyInfoActivity>(
                        values = mutableListOf(
                            CompanyInfoActivity.COMPANY_ID to consumersId!!,
                            CompanyInfoActivity.COMPANY_NAME to companyName!!
                        )
                    )
                } else {
                    showIdentityAuthDialog()
                }
            }
        })
    }

    private fun showIdentityAuthDialog() {
        activity?.run {
            FDialog.newInstance().apply {
                options = Options().apply {
                    isTransparent = true
                }
                setOnDismissListener(object : FDialogInterface.OnDismissListener {
                    override fun onDismiss(dialog: FDialogInterface) {

                    }
                })
                setOnBuilderViewListener(object : FDialogInterface.OnBuilderViewListener {
                    override fun onBuilderView(
                        dialog: FDialogInterface,
                        view: View,
                        layoutRes: Int
                    ) {
                        val titleText = view.findViewById<TextView>(R.id.titleText)
                        val messageText = view.findViewById<TextView>(R.id.messageText)
                        val negativeText = view.findViewById<TextView>(R.id.negativeText)
                        val positiveText = view.findViewById<TextView>(R.id.positiveText)
                        titleText.text = "系统提示"
                        messageText.text = "你还未进行身份认证绑定公司,赶快去认证吧"
                        negativeText.text = "以后再说"
                        positiveText.text = "去认证"
                        positiveText.setOnClickListener {
                            dialog.dismiss()
                            toIdentityAuthentication()
                        }

                        negativeText.setOnClickListener {
                            dialog.dismiss()
                        }
                    }
                })
                show(supportFragmentManager, "identityAuth")
            }
        }
    }

    private fun toIdentityAuthentication() {
        PreferenceHelper.getUserInfo({
            when (it.bindingStatus) {
                0 -> showIdentityAuthTipDialog("你的身份正在认证中,请耐心等待。")
                1 -> showIdentityAuthTipDialog("你的身份已认证成功!")
                else -> startKtxActivity<IdentityAuthActivity>()
            }
        })
    }

    private fun showIdentityAuthTipDialog(tip: String) {
        activity?.run {
            FDialog.newInstance().apply {
                options = Options().apply {
                    isTransparent = true
                }
                setOnDismissListener(object : FDialogInterface.OnDismissListener {
                    override fun onDismiss(dialog: FDialogInterface) {

                    }
                })
                setOnBuilderViewListener(object : FDialogInterface.OnBuilderViewListener {
                    override fun onBuilderView(
                        dialog: FDialogInterface,
                        view: View,
                        layoutRes: Int
                    ) {
                        val titleText = view.findViewById<TextView>(R.id.titleText)
                        val messageText = view.findViewById<TextView>(R.id.messageText)
                        val positiveText = view.findViewById<TextView>(R.id.positiveText)
                        titleText.text = "系统提示"
                        messageText.text = tip
                        positiveText.text = "确定"
                        positiveText.setOnClickListener {
                            dialog.dismiss()
                        }
                    }
                })
                show(supportFragmentManager, "identityAuthTip")
            }
        }
    }

    private fun removeBind() {
        activity?.run {
            PreferenceHelper.getUserInfo({
                if (it.bindingStatus == 1) {
                    FDialog.newInstance().apply {
                        options = Options().apply {
                            isTransparent = true
                        }
                        setOnDismissListener(object : FDialogInterface.OnDismissListener {
                            override fun onDismiss(dialog: FDialogInterface) {

                            }
                        })
                        setOnBuilderViewListener(object : FDialogInterface.OnBuilderViewListener {
                            override fun onBuilderView(
                                dialog: FDialogInterface,
                                view: View,
                                layoutRes: Int
                            ) {
                                val titleText = view.findViewById<TextView>(R.id.titleText)
                                val messageText = view.findViewById<TextView>(R.id.messageText)
                                val negativeText = view.findViewById<TextView>(R.id.negativeText)
                                val positiveText = view.findViewById<TextView>(R.id.positiveText)
                                titleText.text = "系统提示"
                                messageText.text = "你确定要和${it.companyName}公司解除绑定吗？"
                                negativeText.text = "取消"
                                positiveText.text = "确定"
                                positiveText.setOnClickListener {
                                    dialog.dismiss()
                                    mViewModel.removeBind()
                                }

                                negativeText.setOnClickListener {
                                    dialog.dismiss()
                                }
                            }
                        })
                        show(supportFragmentManager, "removeBind")
                    }
                } else {
                    showIdentityAuthDialog()
                }
            })
        }
    }

    private fun shareApp() {
        ShareSceneDialogFragment.newInstance(
            mShareSceneList,
            object : ShareSceneDialogFragment.OnShareSceneListener {

                override fun shareScene(scene: String) {
                    activity?.toast("分享功能暂未开放")
                }

                override fun dismiss() {

                }
            }, "分享至"
        ).show(childFragmentManager, "shareApp")
    }

    private fun toContactUs() {

    }

    private fun versionUpdate() {
        Beta.checkUpgrade(true, false)
    }

    private fun logout() {
        activity?.run {
            FDialog.newInstance().apply {
                options = Options().apply {
                    isTransparent = true
                }
                setOnDismissListener(object : FDialogInterface.OnDismissListener {
                    override fun onDismiss(dialog: FDialogInterface) {

                    }
                })
                setOnBuilderViewListener(object : FDialogInterface.OnBuilderViewListener {
                    override fun onBuilderView(
                        dialog: FDialogInterface,
                        view: View,
                        layoutRes: Int
                    ) {
                        val titleText = view.findViewById<TextView>(R.id.titleText)
                        val messageText = view.findViewById<TextView>(R.id.messageText)
                        val negativeText = view.findViewById<TextView>(R.id.negativeText)
                        val positiveText = view.findViewById<TextView>(R.id.positiveText)
                        titleText.text = "系统提示"
                        messageText.text = "你确定要退出登录吗?"
                        negativeText.text = "取消"
                        positiveText.text = "确定"
                        negativeText.setOnClickListener {
                            dialog.dismiss()
                        }
                        positiveText.setOnClickListener {
                            PreferenceHelper.logout()
                            defaultUserView()
                            dialog.dismiss()
                        }
                    }
                })
                show(supportFragmentManager, "logout")
            }
        }

    }


}